/*
** libpq example
** fwaggle@hungryhacker.com
** http://www.hungryhacker.com/
*/
#include <stdio.h>
#include <stdarg.h>
#include "libpq-fe.h"

#define WORD "this is a test"

PGconn *psql;

PGresult *pq_query(const char *format, ...)
{
	va_list argv;
	char *ptrQuery;
	PGresult *result;
	va_start(argv, format);
	vasprintf(&ptrQuery, format, argv);
	va_end(argv);
	if (!ptrQuery)
		return(0);
	result = PQexec(psql, ptrQuery);
	free(ptrQuery);
	return(result);
}

char * pq_escape (char *input)
{
	int len;
	char *output;
	len = strlen(input);
	if (len == 1)
		return(NULL);
	output = malloc((len * 2) + 1);
	if (!output)
		return(NULL);
	PQescapeString(output, input, len);
	return(output);
}

int main (int argc, char **argv)
{
	char *data_safe;
	int i, j;
	PGresult *result;
	psql = PQconnectdb("hostaddr = '192.168.1.3' port = '' dbname = 'db_iamalive' user = 'postgres' password = 'kamal' connect_timeout = '10'");

	/* init connection */
	if (!psql)
	{
		fprintf(stderr, "libpq error: PQconnectdb returned NULL.\n\n");
		exit(0);
	}
	if (PQstatus(psql) != CONNECTION_OK)
	{
		fprintf(stderr, "libpq error: PQstatus(psql) != CONNECTION_OK\n\n");
		exit(0);
	}
	//result = pq_query("SELECT now(), md5('%s');", WORD);
    result = pq_query("SELECT email_id, password, name from tbl_user;");
	if (!result || !(j = PQntuples(result)))
	{
		fprintf(stderr, "libpq error: no rows returned or bad result set\n\n");
		PQfinish(psql);
		exit(0);
	}
	for (i = 0; i < j; i++)
	{
		printf("email id: %s\n", PQgetvalue(result, i, 0));
		printf("password: %s\n", PQgetvalue(result, i, 1));
        printf("name: %s\n", PQgetvalue(result, i, 1));
	}
	PQclear(result);
	if (argc > 1)
	{
		data_safe = pq_escape(argv[1]);
		result = pq_query("SELECT MD5('%s');", data_safe);
		if (!result || PQntuples(result) < 1)
		{
			fprintf(stderr, "libpq error: no results returned or NULL resultset pointer.\n\n");
			PQfinish(psql);
			exit(0);
		}
		printf("data: %s (data safe: %s)\n", argv[0]);
		printf("MD5: %s\n", PQgetvalue(result, 0, 0));
		PQclear(result);
	}
	PQfinish(psql);
}